package org.example.cloud.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.example.cloud.entities.Account;
import org.example.cloud.mapper.AccountMapper;
import org.example.cloud.service.AccountService;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author 宋孟林
 * @description
 * @date: 2025/4/12 10:05
 */
@Slf4j
@Service
public class AccountServiceImpl extends ServiceImpl<AccountMapper, Account> implements AccountService {
    /**
     * 扣减账户余额
     */
    @Override
    public void decrease(Long userId, Long money) {
        log.info("开始从account-service中扣减账户余额");
        LambdaUpdateWrapper<Account> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper.eq(Account::getUserId, userId).ge(Account::getResidue, money)
                .setSql("used = used + " + money + ", residue = residue - " + money);
        this.update(updateWrapper);
        //myTimeOut();
        //int age = 10/0;
        log.info("从account-service中扣减账户余额结束");
    }

    /**
     * 模拟超时异常，全局事务回滚
     */
    private static void myTimeOut() {
        try {
            TimeUnit.SECONDS.sleep(65);
        }
        catch(InterruptedException e) {
            e.printStackTrace();
        }
    }
}
